package main

import (
	"encoding/json"
	"fmt"
)

/*
   序列化： 将结构体对象转换成json格式数据
   反序列化：将json格式数据转换成结构体对象
*/

// 学生
type Student struct {
	Id     int
	Gender string
	Name   string
}

// 班级
type Class struct {
	Title    string
	Students []Student
}

func main() {
	c := Class{
		Title:    "101",
		Students: make([]Student, 0),
	}
	for i := 0; i < 3; i++ {
		std := Student{
			Id:     i,
			Gender: "男",
			Name:   fmt.Sprintf("stu_%v", i),
		}

		c.Students = append(c.Students, std)
	}

	fmt.Printf("%v\n", c)
	//{101 [{0 男 stu_0} {1 男 stu_1} {2 男 stu_2}]}

	/*
	   结构体嵌套结构体 转换成 json
	*/
	strByte, err1 := json.Marshal(c)
	if err1 != nil {
		fmt.Println("json err:", err1)
	}
	fmt.Println(string(strByte))
	/*
		{"Title":"101","Students":[{"Id":0,"Gender":"男","Name":"stu_0"},{"Id":1,"Gender":"男","Name":"stu_1"},{"Id":2,"Gender":"男","Name":"stu_2"}]}
	*/

	/*
	   json转换成 嵌套结构体
	*/
	str := `{"Title":"101","Students":[{"Id":0,"Gender":"男","Name":"stu_0"}]}`
	var c2 = &Class{}
	err2 := json.Unmarshal([]byte(str), c2)
	if err2 != nil {
		fmt.Println("json err:", err2)
	}
	c2.Title = "111"
	fmt.Printf("%#v\n", c2)
	// main.Class{Title:"101", Students:[]main.Student{main.Student{Id:0, Gender:"男", Name:"stu_0"}}}
	fmt.Println(str)
}
